package com.ruowei.modules.member.web.rest;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.common.error.exception.BadRequestAlertException;
import com.ruowei.common.lang.StringUtils;
import com.ruowei.common.querydsl.OptionalBooleanBuilder;
import com.ruowei.modules.foodOrder.domain.QrAddress;
import com.ruowei.modules.member.domain.QQuestion;
import com.ruowei.modules.member.domain.Question;
import com.ruowei.modules.member.repository.QuestionRepository;
import com.ruowei.modules.member.web.dto.QuestionDTO;
import com.ruowei.modules.sys.utils.CommonUtils;
import io.github.jhipster.web.util.PaginationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
@Transactional
@Api(tags = "帮助与反馈")
public class QuestionResource {

    private final QuestionRepository questionRepository;
    private final JPAQueryFactory queryFactory;
    private final QQuestion qQuestion = QQuestion.question1;

    public QuestionResource(QuestionRepository questionRepository, JPAQueryFactory queryFactory) {
        this.questionRepository = questionRepository;
        this.queryFactory = queryFactory;
    }

    @PostMapping("/addQuestions")
    @ApiOperation("新增帮助反馈")
    public ResponseEntity<Question> addQuestion(@RequestParam String problem,
                                                @RequestParam String answer,
                                                @RequestParam String questionType) {
        if (StringUtils.isEmpty(problem)) {
            throw new BadRequestAlertException("请输入问题");
        }
        if (StringUtils.isEmpty(answer)) {
            throw new BadRequestAlertException("请输入答案");
        }
        if (StringUtils.isEmpty(questionType)) {
            throw new BadRequestAlertException("请输入类型");
        }
//        Optional<Question> issue = questionRepository.findByQuestion(problem);
//        if (issue.isPresent()) {
//            throw new BadRequestAlertException("问题已存在");
//        }
        Question question = new Question();
        question.setQuestionCode(CommonUtils.getUUID());
        question.setQuestion(problem);
        question.setAnswer(answer);
        question.setQuestionType(questionType);
        questionRepository.save(question);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/alterQuestion")
    @ApiOperation("修改帮助反馈")
    public ResponseEntity<Question> alterQuestion(@RequestParam String questionCode,
                                                  @RequestParam String problem,
                                                  @RequestParam String answer) {
        Optional<Question> question = questionRepository.findByQuestionCode(questionCode);
        if (!question.isPresent()) {
            throw new BadRequestAlertException("帮助反馈信息不存在");
        }
        Question issue = question.get();
//        boolean exist = questionRepository.existsByQuestionAndQuestionCodeNot(problem, questionCode);
//        if (exist) {
//            throw new BadRequestAlertException("问题已存在");
//        }
        if (StringUtils.isNotEmpty(problem)) {
            issue.setQuestion(problem);
        }
        if (StringUtils.isNotEmpty(answer)) {
            issue.setAnswer(answer);
        }
        Question aQuestion = questionRepository.save(issue);
        return ResponseEntity.ok(aQuestion);
    }


    @DeleteMapping("/deleteQuestion")
    @ApiOperation("删除帮助反馈")
    public ResponseEntity<Void> deleteQuestion(@RequestParam String questionCode) {
        Optional<Question> question = questionRepository.findByQuestionCode(questionCode);
        if (!question.isPresent()) {
            throw new BadRequestAlertException("帮助反馈信息不存在");
        }
        Question problem = question.get();
        questionRepository.delete(problem);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/getquestionList")
    @ApiOperation("获取帮助反馈列表")
    public ResponseEntity<List<Question>> getQuestions(@RequestParam(required = false) String questionType, Pageable pageable) {
        OptionalBooleanBuilder predicate = new OptionalBooleanBuilder()
            .notEmptyAnd(qQuestion.questionType::eq, questionType);
        JPAQuery<Question> jpaQuery = queryFactory.select(Projections.bean(Question.class, qQuestion.id, qQuestion.question,
            qQuestion.questionCode, qQuestion.answer, qQuestion.questionType))
            .from(qQuestion)
            .where(predicate.build())
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize());
        Page<Question> page = new PageImpl<>(jpaQuery.fetch(), pageable, jpaQuery.fetchCount());
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    @GetMapping("/getQuestion")
    @ApiOperation("获取帮助反馈详情")
    public ResponseEntity<Question> getQuestionDetail(@RequestParam String questionCode) {
        Optional<Question> question = questionRepository.findByQuestionCode(questionCode);
        if (!question.isPresent()) {
            throw new BadRequestAlertException("帮助反馈信息不存在");
        }
        Question problem = question.get();
        return ResponseEntity.ok(problem);
    }

    @GetMapping("/applet/questions")
    @ApiOperation("获取问题列表-小程序")
    public ResponseEntity<List<QuestionDTO>> getAllQuestions(@RequestParam String questionType) {
        List<QuestionDTO> dtoList = new ArrayList<>();
        BooleanBuilder builder = new BooleanBuilder()
            .and(qQuestion.questionType.eq(questionType));
        queryFactory.selectFrom(qQuestion)
            .where(builder)
            .fetch()
            .forEach(question -> {
                QuestionDTO dto = new QuestionDTO();
                dto.setQuestionCode(question.getQuestionCode());
                dto.setQuestion(question.getQuestion());
                dtoList.add(dto);
            });
        return ResponseEntity.ok(dtoList);
    }

    @GetMapping("/applet/getQuestion")
    @ApiOperation("获取答案详情-小程序")
    public ResponseEntity<Question> getQuestion(@RequestParam String questionCode) {
        Optional<Question> question = questionRepository.findByQuestionCode(questionCode);
        if (!question.isPresent()) {
            throw new BadRequestAlertException("帮助反馈信息不存在");
        }
        Question problem = question.get();
        return ResponseEntity.ok(problem);
    }
}
